package com.example.weatherforecast

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.weatherforecast.databinding.ActivityMainBinding
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        thread {
            val str: String? = readFileFromRaw(R.raw.citycode)
            val gson = Gson()
            val CityType = object : TypeToken<List<CityItem>>() {}.type
            val cities: List<CityItem> = gson.fromJson(str, CityType)

            // 过滤掉没有城市代码的城市
            val filteredCities = cities.filter { it.city_code.isNotEmpty() }

            runOnUiThread {
                val adapter =
                    ArrayAdapter(this, android.R.layout.simple_list_item_1, filteredCities)
                binding.listView.adapter = adapter
                binding.listView.setOnItemClickListener { _, _, position, _ ->
                    val cityCode: String = filteredCities[position].city_code
                    val intent = Intent(this, MainActivity2::class.java)
                    intent.putExtra("city_code", cityCode)
                    startActivity(intent)
                }
                Log.d("MainActivity", "cities: $filteredCities")
            }
        }
    }

        fun readFileFromRaw(rewName: Int): String? {
            try {
                val inputReader = InputStreamReader(resources.openRawResource(rewName))
                val bufReader = BufferedReader(inputReader)
                var line: String? = ""
                var result: String? = ""
                while (bufReader.readLine().also({ line = it }) != null) {
                    result += line
                }
                return result
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return ""
        }
}